#include "str_util.h"
#include <sstream>
#include "../include/HashTable.h"
#include "string.h"
#include "tostring.h"

int STRAPI_DataSize(IN U64 u64Size, OUT char* pszResult)
{
    int iRet       = -1;
    double dfSize  = (I64)u64Size;
    int iType      = 0; // 0表示小于1024,1表示大于等于1024小于1000TB,2表示大于等于1000TB
    char szUnit[3] = " B";

    if(dfSize >= 1024)
    {
        dfSize    = dfSize / 1024;
        szUnit[0] = 'K';
        iType     = 1;
        if(dfSize >= 1024)
        {
            dfSize    = dfSize / 1024;
            szUnit[0] = 'M';
            if(dfSize >= 1024)
            {
                dfSize    = dfSize / 1024;
                szUnit[0] = 'G';
                if(dfSize >= 1024)
                {
                    dfSize    = dfSize / 1024;
                    szUnit[0] = 'T';
                    if(dfSize >= 1000) iType = 2;
                }
            }
        }
    }

    switch(iType)
    {
    case 0:
        iRet = sprintf(pszResult, "%I64u", u64Size);
        break;
    case 1:
        iRet = sprintf(pszResult, "%.1f", dfSize);
        break;
    case 2:
        iRet = sprintf(pszResult, "%.0f", dfSize);
        break;
    default:
        goto _Exit;
        break;
    }

    if(szUnit[0] == ' ') strcpy(szUnit, "B");
    strcat(pszResult, szUnit);
_Exit:
    return iRet;
}

int STRAPI_StringToArray(const char* pszIn, STD_ARRAY<U32>& objOut, const char* pcMode)
{
    int iResult, iTmp;
    int iRead = 0, iLenIn;
    const char* pcFind;
    pair<const char*, int> stData;
    char caData[32];

    if(pszIn == nullptr || pcMode == nullptr) return COMMON_ERR_INV_ARGS;

    iLenIn = strlen(pszIn);
    objOut.clear();

    while(iRead < iLenIn)
    {
        stData.first  = pszIn + iRead;
        stData.second = 0;
        pcFind        = strchr(pszIn + iRead, pcMode[0]);
        if(pcFind)
        {
            stData.second = pcFind - pszIn - iRead;
            iRead += stData.second + 1;
        }
        else
        {
            stData.second = iLenIn - iRead;
            iRead += stData.second;
        }
        if(stData.second <= 0) break;
        if(stData.second > 30) return CUSTOM_ERR; // 数字过大无法解析

        memcpy(caData, stData.first, stData.second);
        caData[stData.second] = 0;

        iResult = atoi(caData);
        objOut.push_back(iResult);
    }

    return 0;
}

int STRAPI_ArrayToString(const STD_ARRAY<U32>& objIn, OUT string& strOut, const char* pcMode)
{
    int i;
    ostringstream objStream;

    if(pcMode == nullptr) return COMMON_ERR_INV_ARGS;

    for(i = 0; i < objIn.size() - 1; i++)
    {
        objStream << objIn[i] << pcMode[0];
    }
    objStream << objIn[i];

    strOut = objStream.str();
    return 0;
}
